// 把外链的标签 变成内联
const HtmlWebpackPlugin = require('html-webpack-plugin');

class InlineSourcePlugin{
  constructor({ match }) {
    this.match = match
  }

  processTag(tag, compilation) { // 处理某一个标签
    console.log('------');
    console.log(tag);
    let newTag, url
    if (tag.tagName === 'link' && this.match.test(tag.attributes.href)) {
      newTag = {
        tagName: 'style',
        attributes: { type: 'text/css' }
      }
      url = tag.attributes.href
    } else if (tag.tagName === 'script' && this.match.test(tag.attributes.src)) {
      newTag = {
        tagName: 'script',
        attributes: { type: 'application/javascript' }
      }
      url = tag.attributes.src
    }
    if (url) {
      newTag.innerHTML = compilation.assets[url].source() // 文件的内容放到innerHTML属性上
      delete compilation.assets[url] // 删除掉 原有应该生成的资源
      return newTag
    }
    console.log(newTag);
    return tag
  }

  // 处理引入标签的数据
  processTags(data, compilation) {
    const headTags = []
    const bodyTags = []
    data.headTags.forEach(headTag => {
      headTags.push(this.processTag(headTag, compilation))
    })
    data.bodyTags.forEach(bodyTag => {
      bodyTags.push(this.processTag(bodyTag, compilation))
    })

    return { ...data, headTags, bodyTags }
  }

  apply(compiler) {
    // 要通关webpackPlugin来实现这个功能
    compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
      HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync('alterPlugin', (data, cb) => {
        console.log(data);
        data = this.processTags(data, compilation)
        cb(null, data)
      })
    })
  }
}

module.exports = InlineSourcePlugin